from PySide6.QtWidgets import QDialog,QMessageBox
from PySide6.QtCore import QDate
from sqlalchemy.orm import Session
import datetime
from views.learningexperience.operationlearn import Ui_operationlearn
from settings.publicvar import engine
from views.learningexperience.model.learningexperience import LearningExperience
from views.person.model.person import PersonBaseInfo

class OperationLeanView(QDialog,Ui_operationlearn):
    def __init__(self,is_state,data):
        super().__init__()
        self.setupUi(self)
        self.if_state(is_state)
        self.setFormStructure(data)
        self.deletebtn.clicked.connect(self.deleteFun)
        self.addbtn.clicked.connect(self.addFun)
        self.name.editingFinished.connect(self.nameFinishedFun)
        self.changebtn.clicked.connect(self.changeFun)

    def if_state(self,is_state):
        if is_state == 'add':
            self.titlelable.setText('添加学习经历')
            self.changebtn.hide()
            self.deletebtn.hide()
            self.IDcard.setText('身份证')
            self.name.setPlaceholderText('检查人员信息是否存在')
        elif is_state == 'delete':
            self.titlelable.setText('删除学习经历')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
        elif is_state == 'change':
            self.titlelable.setText('修改学习经历')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.deletebtn.hide()
        else:
            self.titlelable.setText('查看学习经历')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
            self.deletebtn.hide()

    def setFormStructure(self,data):
        if data:
            self.idx.setText(data[0])
            self.name.setText(data[1])
            date = QDate.fromString(data[2], "yyyy-MM-dd")
            if date.isValid():
                self.start_date.setDate(date)
            else:
                self.start_date.setDate(QDate(1, 1, 1))
                self.start_date.setSpecialValueText("请选择日期")
            date = QDate.fromString(data[3], "yyyy-MM-dd")
            if date.isValid():
                self.end_date.setDate(date)
            else:
                self.end_date.setDate(QDate(1, 1, 1))
                self.end_date.setSpecialValueText("请选择日期")
            self.school.setText(data[4])
            self.education_qualifications.setCurrentText(data[5])
            self.professional.setText(data[6])
            self.degreen.setCurrentText(data[7])
            self.degreen_name.setText(data[8])
            self.degreen_number.setText(data[9])
            self.education_mode.setCurrentText(data[10])
            self.school_year.setText(data[11])
            self.graduate_number.setText(data[12])
            self.witness.setText(data[13])
            self.mark.setText(data[14])

    # 获取表单数据
    def getFormData(self):
        idx = self.idx.text().strip()
        name = self.name.text().strip()
        start_date = self.start_date.date()
        start_date = datetime.date(start_date.year(),start_date.month(),start_date.day())
        end_date = self.end_date.date()
        end_date = datetime.date(end_date.year(), end_date.month(), end_date.day())
        school = self.school.text().strip()
        education_qualifications = self.education_qualifications.currentText().strip()
        professional = self.professional.text().strip()
        degreen = self.degreen.currentText().strip()
        degreen_name = self.degreen_name.text().strip()
        degreen_number = self.degreen_number.text().strip()
        education_mode = self.education_mode.currentText().strip()
        school_year = self.school_year.text().strip()
        graduate_number = self.graduate_number.text().strip()
        witness = self.witness.text().strip()
        mark = self.mark.text().strip()

        return [idx,{'start_date':start_date,'end_date':end_date,'school':school,
                     'education_qualifications':education_qualifications,'professional':professional,
                     'degreen':degreen,'degreen_name':degreen_name,'degreen_number':degreen_number,
                     'education_mode':education_mode,'school_year':school_year,'graduate_number':graduate_number,
                     'witness':witness,'mark':mark}]

    # 删除
    def deleteFun(self):
        idx = self.idx.text()
        with Session(engine) as session,session.begin():
            session.query(LearningExperience).filter(LearningExperience.id == idx).delete()
            QMessageBox.information(None,'成功','%s删除成功'%self.name.text())
            # session.query(LearningExperience).delete()
        self.close()

    # 添加
    def addFun(self):
        data = self.getFormData()
        if data[0] == '':
            with Session(engine) as session,session.begin():
                data[1]['name_id'] = self.name_id
                learn = LearningExperience(**data[1])
                session.add(learn)
            QMessageBox.information(None,'成功','%s添加成功'%self.name.text())
        self.close()

    def changeFun(self):
        idx = self.idx.text().strip()
        data = self.getFormData()
        session = Session(engine)
        session.query(LearningExperience).filter(LearningExperience.id == idx).update(data[1])
        session.commit()
        with Session(engine) as session,session.begin():
            learn = session.query(LearningExperience).filter(LearningExperience.id == idx).update(data[1])
        self.close()

    def nameFinishedFun(self):
        IDcard = self.name.text().strip()
        with Session(engine) as session,session.begin():
            try:
                personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard == IDcard).one()
                if not personbase.learningexperiences:
                    self.name.setText(personbase.name)
                    self.name_id = personbase.id
                else:
                    QMessageBox.critical(None, '失败', '数据已经增加了，不用添加！')
                    self.close()
            except:
                QMessageBox.critical(None,'失败','没有找到基本信息，请选增加基本信息,请检查身份证是否输错！')